package com.redwood.report.activity.bak;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.redwood.report.ItemDecoration.FullyGridLayoutManager;
import com.redwood.report.R;
import com.redwood.report.adapter.bak.AddBaoXiuAddAdapter;
import com.redwood.report.base.BaseActivity;
import com.redwood.report.common.Config;
import com.redwood.report.common.Constant;
import com.redwood.report.entity.ServiceResult;
import com.redwood.report.entity.bak.SheBeiInfo;
import com.redwood.report.entity.bak.SheBeiOneInfo;
import com.redwood.report.entity.bak.been.AddBeen;
import com.redwood.report.entity.bak.been.ImageBeen;
import com.redwood.report.event.QRChangeEvent;
import com.redwood.report.event.SheBeiChangeEvent;
import com.redwood.report.event.ShuaXinEvent;
import com.redwood.report.net.Api;
import com.redwood.report.net.NetUtils;
import com.redwood.report.net.UpLoadImageUtil;
import com.redwood.report.util.KeyboardUtils;
import com.redwood.report.util.PhotoUtils;
import com.redwood.report.util.ToastUtils;
import com.redwood.report.util.Utils;
import com.redwood.report.util.actionbar.LightStatusBarUtils;
import com.redwood.report.util.actionbar.ToolbarUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 添加报修
 * Created by Supeng on 2018/10/12.
 */

public class AddBaoXiuActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.title_bar)
    RelativeLayout titleBar;
    @BindView(R.id.root_layout)
    LinearLayout rootLayout;
    @BindView(R.id.iv_saoma)
    ImageView ivSaoma;
    @BindView(R.id.et_shebei)
    EditText etSheiBei;
    @BindView(R.id.rv_image)
    RecyclerView rvImage;
    @BindView(R.id.et_bianhao)
    EditText etBianhao;
    @BindView(R.id.et_miaoshu)
    EditText etMiaoshu;
    @BindView(R.id.save_btn)
    Button saveBtn;
    @BindView(R.id.tv_shebei_sel)
    TextView tvShebeiSel;
    private BaseQuickAdapter addBaoXiuAddAdapter;
    private ArrayList<MultiItemEntity> mDataList = new ArrayList<>();
    private PhotoUtils mPhotoUtils;
    private String renyuanType = Constant.BAOXIUREN;
    private String title1 = "添加报修";
    private String title2 = "添加巡检";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_baoxiu);
        unbinder = ButterKnife.bind(this);
        //标题栏颜色
        ToolbarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.blueColorAppKey));
        //深色主题 true字颜色为深色 false 为白色标题字
        LightStatusBarUtils.setLightStatusBar(this, false);
        if (Config.isUserLogin()) {
            renyuanType = Config.getUserInfo().getRole();
        }
        initView();
        initData();
        initPic();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQRChangeEven(QRChangeEvent event) {
        loadByServer(event.qr);
    }
    public void loadByServer(String macId){
        Api.machineGetInfo(getActivity(), macId, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                    SheBeiOneInfo sheBeiOneInfo= (SheBeiOneInfo) rspData;
                    if(sheBeiOneInfo.getInfo()!=null) {
                        SheBeiInfo.DataBean dataBean = sheBeiOneInfo.getInfo();
                        etSheiBei.setText(dataBean.getMacName() + " " + dataBean.getModelNo());
                        etBianhao.setText(dataBean.getMacID());
                    }else {
                        etSheiBei.setText("");
                        etBianhao.setText("");
                        ToastUtils.show("服务器没有此二维码");
                    }
            }

            @Override
            public void failed(String msg) {
                etSheiBei.setText("");
                etBianhao.setText("");
            }

            @Override
            public void onUsedCache(String msg) {

            }
        }, SheBeiOneInfo.class);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSheBeiChangeEvent(SheBeiChangeEvent event) {
        SheBeiInfo.DataBean dataBean = event.dataBean;
        etSheiBei.setText(dataBean.getMacName() + " " + dataBean.getModelNo());
        etBianhao.setText(dataBean.getMacID());
    }

    private void initView() {
        ivBack.setOnClickListener(this);
        ivSaoma.setOnClickListener(this);
        etSheiBei.setOnClickListener(this);
        tvShebeiSel.setOnClickListener(this);
        saveBtn.setOnClickListener(this);
        initImageAdapter();
        if (renyuanType.equals(Constant.BAOXIUREN)) {
            tvTitle.setText(title1);
        } else if (renyuanType.equals(Constant.GUANLIYUAN) || renyuanType.equals(Constant.WEIXIUREN)) {
            tvTitle.setText(title2);
        }
    }


    private void initImageAdapter() {
        mDataList.clear();
        AddBeen addBeen = new AddBeen();
        mDataList.add(addBeen);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        rvImage.setLayoutManager(manager);
        addBaoXiuAddAdapter = new AddBaoXiuAddAdapter(mDataList);
        addBaoXiuAddAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent=new Intent(getActivity(),PicturePreviewActivity.class);
                intent.putExtra("url",Constant.getBaseUrl()+((ImageBeen)adapter.getData().get(position)).getPath());
                startActivity(intent);
            }
        });
        addBaoXiuAddAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_add:
                        //最大上传6张图片
                        if (mDataList.size() > 7) {
                            return;
                        }
                        new AlertDialog.Builder(getActivity())
                                .setTitle("选择图片")
                                .setItems(new String[]{"拍照", "从相册"},
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                                if (which == 0) {
                                                    //使用拍照 带配置
                                                    mPhotoUtils.takePicture(getActivity());
                                                } else {
                                                    //单选打开相册 带配置
                                                    mPhotoUtils.selectPicture(getActivity());
                                                }
                                            }
                                        }
                                )
                                .show();
                        break;
                }
            }
        });
        rvImage.setAdapter(addBaoXiuAddAdapter);
    }

    private void initData() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PhotoUtils.INTENT_CROP:
            case PhotoUtils.INTENT_TAKE:
            case PhotoUtils.INTENT_SELECT:
                mPhotoUtils.onActivityResult(getActivity(), requestCode, resultCode, data);
                break;
        }
    }

    private void initPic() {
        mPhotoUtils = new PhotoUtils(new PhotoUtils.OnPhotoResultListener() {
            @Override
            public void onPhotoResult(Uri uri) {
                if (uri != null && !TextUtils.isEmpty(uri.getPath())) {
                    String mPicPath = Utils.getPath(getActivity(), uri);
                    if (!TextUtils.isEmpty(mPicPath)) {
                        //+ Config.getUserInfo().getUserCode()
                        uploadPhoto(mPicPath, "/api/MachineWX/upload");
                    }
                }
            }

            @Override
            public void onPhotoCancel() {

            }
        });
    }

    /**
     * 图片上传
     */
    private void uploadPhoto(final String filename, final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    new UpLoadImageUtil().uploadPic(filename, url, mHistoryImageHandler);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    protected Handler mHistoryImageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String resultJson = msg.getData().getString("result");
            if (!TextUtils.isEmpty(resultJson)) {
                try {
                    JSONObject jsonObject2 = new JSONObject(resultJson);
                    int code = jsonObject2.getInt("recode");
                    String message = jsonObject2.getString("msg");
                    String filePath=jsonObject2.getString("filePath");
                    if (code==1) {
                        ImageBeen imageBeen=new ImageBeen();
                        imageBeen.setPath(filePath);
                        addBaoXiuAddAdapter.getData().add(addBaoXiuAddAdapter.getData().size()-1,imageBeen);
                        addBaoXiuAddAdapter.notifyItemInserted(addBaoXiuAddAdapter.getData().size()-1);
                    } else {
                        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_saoma:
                KeyboardUtils.hideSoftInput(v,getActivity());
              //  startActivity(new Intent(getActivity(), CameraCaptureActivity.class));
                break;
            case R.id.et_shebei:
                break;
            case R.id.tv_shebei_sel:
                KeyboardUtils.hideSoftInput(v,getActivity());
                Intent intent=new Intent(getActivity(),SelectedSheBeiActivity.class);
                startActivity(intent);
                break;
            case R.id.save_btn:
                KeyboardUtils.hideSoftInput(v,getActivity());
                if(TextUtils.isEmpty(etBianhao.getText().toString())){
                    ToastUtils.show("请选择设备");
                    return;
                }
                if(TextUtils.isEmpty(etMiaoshu.getText().toString())){
                    ToastUtils.show("请对缺陷进行描述");
                    return;
                }
                addByServer();
                break;
        }
    }

    private void addByServer() {
        String imgUrl="";
        List<MultiItemEntity> imageBeenList=addBaoXiuAddAdapter.getData();
        if(imageBeenList.size()>1) {
            for (MultiItemEntity imageBeenEntity : imageBeenList) {
                if (imageBeenEntity instanceof ImageBeen) {
                    imgUrl = imgUrl + ((ImageBeen) imageBeenEntity).getPath() + "^";
                }
            }
            imgUrl = imgUrl.substring(0, imgUrl.length() - 1);
        }
        Api.baoxiuAdd(getActivity(), etBianhao.getText().toString(),etMiaoshu.getText().toString(),imgUrl, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
               if(rspData.getRecode()==1){
                   EventBus.getDefault().post(new ShuaXinEvent(Constant.WEICHULI));
                   finish();
               }else{
                   ToastUtils.show(rspData.getMsg());
               }
            }

            @Override
            public void failed(String msg) {
                ToastUtils.show(msg);
            }

            @Override
            public void onUsedCache(String msg) {

            }
        }, ServiceResult.class);
    }
}
